<!-- VIP使用情况指示器组件 -->
<template>
	<div class="vip-usage-indicator">
		<a-tooltip placement="bottomRight" :title="getTooltipContent()">
			<div class="usage-icon-wrapper" :class="getUsageStatusClass()" @click="showUsageModal">
				<DatabaseOutlined class="usage-icon" />
				<div v-if="usageStatus === 'warning'" class="warning-dot"></div>
				<div v-if="usageStatus === 'danger'" class="danger-dot"></div>
			</div>
		</a-tooltip>

		<!-- 使用详情模态框 -->
		<a-modal v-model:open="modalVisible" title="使用情况详情" :footer="null" width="500px" class="usage-modal">
			<div v-if="loading" class="loading-container">
				<a-spin size="large" />
			</div>
			<div v-else-if="usageData" class="usage-details">
				<!-- 用户角色信息 -->
				<div class="user-role-section">
					<h4>
						<CrownOutlined />
						用户等级
					</h4>
					<a-tag :color="usageData.isVip ? 'gold' : 'default'" size="large">
						{{ getRoleDisplayName(usageData.userRole) }}
					</a-tag>
					<a-button v-if="!usageData.isVip" type="primary" size="small" @click="goToVipPage" style="margin-left: 8px">
						升级VIP
					</a-button>
				</div>

				<!-- 配置限制 -->
				<div class="limits-section">
					<h4>
						<SettingOutlined />
						配置限制
					</h4>
					<div class="limit-items">
						<div class="limit-item">
							<span class="label">最大Tokens：</span>
							<span class="value">{{ usageData.maxTokens?.toLocaleString() }}</span>
						</div>
						<div class="limit-item">
							<span class="label">最大消息数：</span>
							<span class="value">{{ usageData.maxMessages }}</span>
						</div>
					</div>
				</div>

				<!-- 今日使用情况 -->
				<div class="remaining-section">
					<h4>
						<ClockCircleOutlined />
						今日使用情况
					</h4>
					<div class="remaining-info">
						{{ usageData.remainingInfo }}
					</div>
				</div>

				<!-- 操作按钮 -->
				<div class="action-buttons">
					<a-button @click="refreshUsage" :loading="refreshing">
						<ReloadOutlined />
						刷新数据
					</a-button>
					<a-button type="primary" @click="goToVipPage" v-if="!usageData.isVip"> 升级VIP获得更多权限 </a-button>
				</div>
			</div>
			<div v-else class="error-container">
				<a-result status="error" title="加载失败" sub-title="无法获取使用情况信息">
					<template #extra>
						<a-button type="primary" @click="loadUsageData">重试</a-button>
					</template>
				</a-result>
			</div>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import {
	DatabaseOutlined,
	CrownOutlined,
	SettingOutlined,
	ClockCircleOutlined,
	ReloadOutlined,
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { getUserLimits } from '@/api/vipLimitController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 响应式数据
const modalVisible = ref(false)
const loading = ref(false)
const refreshing = ref(false)
const usageData = ref<any>(null)

// 计算属性
const usageStatus = computed(() => {
	if (!usageData.value) return 'normal'

	// 解析剩余信息来判断使用状况
	const remainingInfo = usageData.value.remainingInfo
	if (remainingInfo.includes('0/')) {
		return 'danger' // 有项目已用完
	}

	// 检查是否接近限制（简单示例：如果有项目使用量超过80%则警告）
	const usagePattern = /(\d+)\/(\d+)/g
	let match
	while ((match = usagePattern.exec(remainingInfo)) !== null) {
		const used = parseInt(match[1])
		const total = parseInt(match[2])
		if (total > 0 && used / total >= 0.8) {
			return 'warning'
		}
	}

	return 'normal'
})

// 方法
const getUsageStatusClass = () => {
	return {
		'status-normal': usageStatus.value === 'normal',
		'status-warning': usageStatus.value === 'warning',
		'status-danger': usageStatus.value === 'danger',
	}
}

const getTooltipContent = () => {
	if (!usageData.value) return '点击查看使用情况'

	const role = getRoleDisplayName(usageData.value.userRole)
	return `${role} | 点击查看详细使用情况`
}

const getRoleDisplayName = (role: string) => {
	const roleMap: Record<string, string> = {
		user: '普通用户',
		vip: 'VIP用户',
		admin: '管理员',
	}
	return roleMap[role] || role
}

const showUsageModal = () => {
	modalVisible.value = true
	if (!usageData.value) {
		loadUsageData()
	}
}

const loadUsageData = async () => {
	if (!loginUserStore.loginUser?.id) {
		return // 静默失败，不显示错误消息
	}

	loading.value = true
	try {
		const response = await getUserLimits()
		if (response.data.code === 0) {
			usageData.value = response.data.data
		} else {
			throw new Error(response.data.message || '获取使用情况失败')
		}
	} catch (error) {
		console.error('获取使用情况失败:', error)
		// 只在用户主动查看时才显示错误消息
		if (modalVisible.value) {
			message.error('获取使用情况失败')
		}
	} finally {
		loading.value = false
	}
}

const refreshUsage = async () => {
	refreshing.value = true
	try {
		await loadUsageData()
		message.success('数据已刷新')
	} finally {
		refreshing.value = false
	}
}

const goToVipPage = () => {
	modalVisible.value = false
	router.push('/user/vip')
}

// 生命周期
onMounted(() => {
	// 初始加载数据（静默加载）
	if (loginUserStore.loginUser?.id) {
		loadUsageData()
	}
})
</script>

<style scoped lang="scss">
.vip-usage-indicator {
	.usage-icon-wrapper {
		width: 32px;
		height: 32px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		cursor: pointer;
		transition: all 0.3s ease;
		background: #f0f0f0;
		border: 2px solid #d9d9d9;
		position: relative;

		&.status-normal {
			background: #f6ffed;
			border-color: #b7eb8f;

			.usage-icon {
				color: #52c41a;
			}

			&:hover {
				background: #d9f7be;
				transform: translateY(-1px);
			}
		}

		&.status-warning {
			background: #fffbe6;
			border-color: #ffe58f;

			.usage-icon {
				color: #faad14;
			}

			&:hover {
				background: #fff1b8;
				transform: translateY(-1px);
			}

			.warning-dot {
				position: absolute;
				top: -2px;
				right: -2px;
				width: 8px;
				height: 8px;
				background: #faad14;
				border-radius: 50%;
				animation: pulse 2s infinite;
			}
		}

		&.status-danger {
			background: #fff2f0;
			border-color: #ffccc7;

			.usage-icon {
				color: #ff4d4f;
			}

			&:hover {
				background: #ffa39e;
				transform: translateY(-1px);
			}

			.danger-dot {
				position: absolute;
				top: -2px;
				right: -2px;
				width: 8px;
				height: 8px;
				background: #ff4d4f;
				border-radius: 50%;
				animation: pulse 2s infinite;
			}
		}

		.usage-icon {
			font-size: 16px;
			transition: all 0.3s ease;
		}
	}
}

.usage-modal {
	:deep(.ant-modal-body) {
		padding: 24px;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 200px;
	}

	.usage-details {
		.user-role-section,
		.limits-section,
		.remaining-section {
			margin-bottom: 24px;

			h4 {
				margin-bottom: 12px;
				color: #262626;
				font-weight: 600;
				display: flex;
				align-items: center;
				gap: 8px;
			}
		}

		.limit-items {
			background: #fafafa;
			padding: 16px;
			border-radius: 8px;
			border: 1px solid #f0f0f0;

			.limit-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 8px;

				&:last-child {
					margin-bottom: 0;
				}

				.label {
					color: #666;
					font-weight: 500;
				}

				.value {
					color: #262626;
					font-weight: 600;
				}
			}
		}

		.remaining-info {
			background: #e6f7ff;
			padding: 16px;
			border-radius: 8px;
			border: 1px solid #91d5ff;
			color: #0050b3;
			font-weight: 500;
			line-height: 1.5;
		}

		.action-buttons {
			display: flex;
			gap: 12px;
			justify-content: flex-end;
			margin-top: 24px;
			padding-top: 16px;
			border-top: 1px solid #f0f0f0;
		}
	}

	.error-container {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 200px;
	}
}

// 动画效果
@keyframes pulse {
	0% {
		transform: scale(1);
		opacity: 1;
	}
	50% {
		transform: scale(1.2);
		opacity: 0.7;
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}
</style>
